package com.bluenode.bounce;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.*;

import com.threed.jpct.*;
import com.threed.jpct.util.*;

import android.graphics.drawable.*;
import android.opengl.*;

public class CubeRenderer implements GLSurfaceView.Renderer {
	private final CubeActivity activity;
	
	private Object3D cube;
	private Light sun;
	private RGBColor back;
	
	private int fps;
	private long time;
	
	private FrameBuffer fb;
	private World world;
  
	private float touchTurn;
	private float touchTurnUp;
	
	public CubeRenderer(CubeActivity activity) {
		this.activity = activity;
	}

	@Override
	public void onSurfaceCreated(GL10 na, EGLConfig config) {
	}

	@Override
	public void onDrawFrame(GL10 arg0) {
		if (touchTurn != 0) {
			cube.rotateY(touchTurn);
			touchTurn = 0;
		}

		if (touchTurnUp != 0) {
			cube.rotateX(touchTurnUp);
			touchTurnUp = 0;
		}

		fb.clear(back);
		world.renderScene(fb);
		world.draw(fb);
		fb.display();

		if (System.currentTimeMillis() - time >= 1000) {
			//Logger.log(fps + "fps");
			fps = 0;
			time = System.currentTimeMillis();
		}
		fps++;
	}

	@Override
	public void onSurfaceChanged(GL10 na, int w, int h) {
		if (fb != null) {
			fb.dispose();
		}
		fb = new FrameBuffer(w, h);

		world = new World();
		world.setAmbientLight(20, 20, 20);

		sun = new Light(world);
		sun.setIntensity(250, 250, 250);

		// Create a texture out of the icon...:-)
		Texture texture = new Texture(BitmapHelper.rescale(BitmapHelper.convert(getIcon()), 64, 64));
		TextureManager.getInstance().addTexture("texture", texture);

		cube = Primitives.getCube(10f);
		cube.calcTextureWrapSpherical();
		cube.setTexture("texture");
		cube.strip();
		cube.build();

		world.addObject(cube);

		Camera cam = world.getCamera();
		cam.moveCamera(Camera.CAMERA_MOVEOUT, 50);
		cam.lookAt(cube.getTransformedCenter());

		SimpleVector sv = new SimpleVector();
		sv.set(cube.getTransformedCenter());
		sv.y -= 100;
		sv.z -= 100;
		sun.setPosition(sv);
		MemoryHelper.compact();
		
	}

	private Drawable getIcon(){
		return activity.getResources().getDrawable(R.drawable.ic_launch_bluenode);
	}
}
